# -*- coding: utf-8 -*-
import webapp2
import exceptions
from google.appengine.ext import db

from schoolkid import Schoolkid
from parallel import Parallel
from webapp2 import uri_for


class ViewLists(webapp2.RequestHandler):

    def get(self, *args, **kwargs):
        total_number_of_pupils = 0
        parallels = Parallel.query().order(Parallel.name)
        self.response.write("""<html><body>
        <script>
            function openList(var id){
                var elem = document.getElementById(id);
                elem.style.display = "block";
            }
        </script>
        Список учеников по параллелям: <ul>""")
        pupilsList = {}
        for pupil in Schoolkid.query():
            total_number_of_pupils += 1
            if pupil.parallel not in pupilsList.keys():
                pupilsList[pupil.parallel] = [pupil]
            else:
                pupilsList[pupil.parallel].append(pupil)

        for parallel in pupilsList.keys():
            self.response.write('<li>%s(%d)<ul>' % (parallel, len(pupilsList[parallel])))
            for pupil in pupilsList[parallel]:
                self.response.write('<li>%s %s %d</li>' % (pupil.surname, pupil.name, pupil.grade))
            self.response.write('</ul></li>')

        self.response.write("""</ul>
        Pupils: %d <br>
        <form action = "%s" method = "post"><input type="submit" value="Clear values"></form>
        <form action = "%s" method = "post">
            <label for = "surname">Type your surname:</label>
            <input id = "surname" type = "text" name = "surname"><br>
            <label for = "name">Your name:</label>
            <input id = "name" type = "text" name = "name"><br>
            <label for = "grade">Your class:</label>
            <select id = "grade" name = "grade">""" % (total_number_of_pupils, uri_for('clear'), uri_for('add')))

        min_grade = 5
        max_grade = 10
        for grade in range(min_grade, max_grade + 1):
            self.response.write('<option>%d</option>' % (grade))

        self.response.write("""</select><br>
        <label for = "parallel"> Select parallel:</label>
        <select id = "parallel" name = "parallel">""")
        for parallel in parallels:
            self.response.write('<option>%s</option>' % parallel.name)
        self.response.write("""</select><input type = "submit" name = "Add"><br>
        <a href = "/parallels">Configure parallels</a>
        </body></html>""")


class AddPupil(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddPupil, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        try:
            surname = self.request.get('surname')
            name = self.request.get('name')
            grade = int(self.request.get('grade'))
            paral = self.request.get('parallel')
            if surname == "" or name == "":
                self.response.write('<script>alert("Пожалуйста, заполните оба поля")</script>')
                self.redirect(uri_for('show'))
                return
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        new_pupil = Schoolkid(surname = surname, name = name, grade = grade, parallel = paral)
        new_pupil.put()
        par_query = Parallel.query().order(Parallel.name)
        for par_key in Parallel.query().iter(keys_only = True):
            par = Parallel.get_by_id(par_key.id())
            if par.name == new_pupil.parallel:
                par.consist.append(new_pupil)
                break
        self.redirect(uri_for('show'))


class ViewParallels(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        parallels = Parallel.query().order(Parallel.name)
        self.response.write('<html><body><ul>')
        for par in parallels:
            self.response.write('<li>%s</li>' % par.name)

        self.response.write("""</ul>
        <form action = "%s" method = "post"><input type="submit" value="Clear values"></form>
        <form action = "%s" method = "post">
            <label for = "par">Type new parallel:</label>
            <input id = "par" name = "par" type = "text">
            <input type = "submit" name = "Addpar">
        </form>
        <a href = "/">Back to the main</a></body></html>""" % (uri_for('clearpar'), uri_for('addpar')))

class ClearParallels(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearParallels, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        total = 0
        for par_key in Parallel.query().iter(keys_only = True):
            par_key.delete()
        self.redirect(uri_for('show'))

class ClearPupils(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearPupils, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        total = 0
        for key in Schoolkid.query().iter(keys_only = True):
            key.delete()

        self.redirect(uri_for('show'))

class AddParallels(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddParallels, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        try:
            name = self.request.get('par')
        except exceptions.ValueError:
            self.redirect(uri_for('showpar'))
            return
        new_par = Parallel(name = name)
        new_par.put()
        self.redirect(uri_for('showpar'))
